package com.ruoyi.web.controller.system;

import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.TeacherInfo;
import com.ruoyi.system.service.ITeacherInfoService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 教师信息Controller
 *
 * @author ltr
 * @date 2024-10-21
 */
@RestController
@RequestMapping("/system/teacher")
public class TeacherInfoController extends BaseController
{
    @Autowired
    private ITeacherInfoService teacherInfoService;

    // ==================== 原有功能（教师个人端） ====================

    /**
     * 查询教师信息列表
     */
    @PreAuthorize("@ss.hasPermi('system:teacher:list')")
    @GetMapping("/list")
    public TableDataInfo list(TeacherInfo teacherInfo)
    {
        startPage();
        List<TeacherInfo> list = teacherInfoService.selectTeacherInfoList(teacherInfo);
        return getDataTable(list);
    }

    /**
     * 导出教师信息列表
     */
    @PreAuthorize("@ss.hasPermi('system:teacher:export')")
    @Log(title = "教师信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TeacherInfo teacherInfo)
    {
        List<TeacherInfo> list = teacherInfoService.selectTeacherInfoList(teacherInfo);
        ExcelUtil<TeacherInfo> util = new ExcelUtil<TeacherInfo>(TeacherInfo.class);
        util.exportExcel(response, list, "教师信息数据");
    }

    /**
     * 获取教师信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:teacher:query')")
    @GetMapping(value = "/{teacherId}")
    public AjaxResult getInfo(@PathVariable("teacherId") Long teacherId)
    {
        return success(teacherInfoService.selectTeacherInfoByTeacherId(teacherId));
    }

    /**
     * 根据用户ID获取教师信息
     */
    @GetMapping(value = "/user/{userId}")
    public AjaxResult getInfoByUserId(@PathVariable("userId") Long userId)
    {
        return success(teacherInfoService.selectTeacherInfoByUserId(userId));
    }

    /**
     * 获取当前登录教师的信息
     */
    @GetMapping("/profile")
    public AjaxResult getProfile()
    {
        Long userId = getUserId();
        TeacherInfo teacherInfo = teacherInfoService.selectTeacherInfoByUserId(userId);
        return success(teacherInfo);
    }

    /**
     * 新增教师信息（原有的简单新增）
     */
    @PreAuthorize("@ss.hasPermi('system:teacher:add')")
    @Log(title = "教师信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TeacherInfo teacherInfo)
    {
        return toAjax(teacherInfoService.insertTeacherInfo(teacherInfo));
    }

    /**
     * 修改教师信息
     */
    @PreAuthorize("@ss.hasPermi('system:teacher:edit')")
    @Log(title = "教师信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TeacherInfo teacherInfo)
    {
        return toAjax(teacherInfoService.updateTeacherInfo(teacherInfo));
    }

    /**
     * 保存或更新教师信息（个人中心使用）
     */
    @Log(title = "教师信息", businessType = BusinessType.UPDATE)
    @PutMapping("/profile")
    public AjaxResult saveOrUpdate(@RequestBody TeacherInfo teacherInfo)
    {
        // 设置当前用户ID
        teacherInfo.setUserId(getUserId());
        return toAjax(teacherInfoService.saveOrUpdateTeacherInfo(teacherInfo));
    }

    /**
     * 删除教师信息
     */
    @PreAuthorize("@ss.hasPermi('system:teacher:remove')")
    @Log(title = "教师信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{teacherIds}")
    public AjaxResult remove(@PathVariable Long[] teacherIds)
    {
        return toAjax(teacherInfoService.deleteTeacherInfoByTeacherIds(teacherIds));
    }

    // ==================== 新增：管理员端功能 ====================

    /**
     * 新增教师信息并自动创建系统账号（管理员端）
     */
    @PreAuthorize("@ss.hasPermi('system:teacher:add')")
    @Log(title = "新增教师（创建账号）", businessType = BusinessType.INSERT)
    @PostMapping("/addWithAccount")
    public AjaxResult addWithAccount(@Validated @RequestBody TeacherInfo teacherInfo)
    {
        // 校验工号是否已存在
        if (!teacherInfoService.checkTeacherNoUnique(teacherInfo))
        {
            return error("新增教师'" + teacherInfo.getTeacherNo() + "'失败，工号已存在");
        }

        teacherInfo.setCreateBy(getUsername());
        return toAjax(teacherInfoService.insertTeacherInfoWithAccount(teacherInfo));
    }

    /**
     * 批量导入教师信息（自动创建系统账号）
     */
    @PreAuthorize("@ss.hasPermi('system:teacher:import')")
    @Log(title = "批量导入教师", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<TeacherInfo> util = new ExcelUtil<TeacherInfo>(TeacherInfo.class);
        List<TeacherInfo> teacherList = util.importExcel(file.getInputStream());
        String operName = getUsername();
        String message = teacherInfoService.importTeacherInfo(teacherList, updateSupport, operName);
        return success(message);
    }

    /**
     * 下载导入模板
     */
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response)
    {
        ExcelUtil<TeacherInfo> util = new ExcelUtil<TeacherInfo>(TeacherInfo.class);
        util.importTemplateExcel(response, "教师信息数据");
    }

    /**
     * 重置教师账号密码为123456
     */
    @PreAuthorize("@ss.hasPermi('system:teacher:resetPwd')")
    @Log(title = "重置教师密码", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd/{teacherId}")
    public AjaxResult resetPwd(@PathVariable Long teacherId)
    {
        return toAjax(teacherInfoService.resetTeacherPassword(teacherId, getUsername()));
    }
}